package com.sftz.modules.minapp.mystudy.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sftz.assets.enums.CurriculumResourcesEnum;
import com.sftz.assets.enums.OrderTypeEnum;
import com.sftz.assets.enums.StudyStateEnum;
import com.sftz.assets.enums.YesOrNoEnum;
import com.sftz.framework.rersult.MobileResult;
import com.sftz.framework.util.CheckTimeUtil;
import com.sftz.modules.minapp.mystudy.dto.ExpireDto;
import com.sftz.modules.minapp.mystudy.dto.MyCourseTotalDto;
import com.sftz.modules.minapp.mystudy.dto.MyStudyDto;
import com.sftz.modules.minapp.mystudy.form.MyStudyForm;
import com.sftz.modules.minapp.resourceRecord.service.StudentOtherCourseScoreViewService;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.MapUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

/**
 * 我的学习
 * @author   王宏伟
 * @Date	 2018年12月11日
 */
@IocBean
public class MyStudyService {
	private static final Log log = Logs.get();
	@Inject
	protected IDbDao dbDao;
	@Inject
	protected Dao nutDao;
	@Inject
	protected SqlManager sqlManager;
	@Inject
	private StudentOtherCourseScoreViewService studentOtherCourseScoreViewService;

	/**
	 * 学习列表
	 * @author	王宏伟
	 * @Date	2018年12月17日
	 */
	public Map<String, Object> dataList(MyStudyForm form) {
		String token = form.getToken();
		//id
		Integer userId = RedissionUserCache.getUserId(token);
		//测试使用userId
		//userId = 32;
		Integer pageNumber = form.getPageNumber();
		Integer pageSize = form.getPageSize();
		//获取状态
		Integer learningState = form.getLearningState();
		int pageNum = (pageNumber - 1) * pageSize;
		Sql sql = Sqls.create(sqlManager.get("minapp_mystudy_list"));
		sql.setParam("userId", userId);
		sql.setParam("course", OrderTypeEnum.COURSE.intKey());
		sql.setParam("series", OrderTypeEnum.COURSESERIES.intKey());
		sql.setParam("pageNumber", pageNum);
		sql.setParam("pageSize", pageSize);
		Cnd cnd = Cnd.NEW();
		if (!Util.isEmpty(learningState)) {
			cnd.and("c.learningState", "=", learningState);
			sql.setCondition(cnd);
		}
		List<MyStudyDto> myStudyList = DbSqlUtil.query(dbDao, MyStudyDto.class, sql);
		//循环判断机构课程下的学期课程是否过期
		//获取查询到数据的id
		ArrayList<String> courseIdList = Lists.newArrayList();
		if (!Util.isEmpty(myStudyList)) {
			try {
				for (MyStudyDto studyCourseDto : myStudyList) {
					//获取提示 
					getHints(studyCourseDto, userId);
					if (studyCourseDto.getCourseType() == 2 && studyCourseDto.getCourseAttr() == 1
							&& !Util.isEmpty(studyCourseDto.getEffectiveStart())
							&& !Util.isEmpty(studyCourseDto.getEffectiveEnd())) {
						//判断课程类型，课程学期，有效时间不为空
						boolean effectiveTime = CheckTimeUtil.belongCalendar(new Date(),
								studyCourseDto.getEffectiveStart(), studyCourseDto.getEffectiveEnd());
						studyCourseDto.setEffectiveTime(effectiveTime);
					}
					courseIdList.add(studyCourseDto.getCourseId().toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
				return MobileResult.error("接口调用失败", null);
			}

		}
		//优化：提示
		//		System.out.println(courseIdList);
		//		getHintsss(courseIdList, userId);

		MyCourseTotalDto myStudyCount = myStudyCount(userId);
		Map<String, Object> map = Maps.newHashMap();
		map.put("myStudyList", myStudyList);
		map.put("pageNumber", pageNumber);
		map.put("pageSize", pageSize);
		map.put("myStudyCount", myStudyCount);
		map.put("pageNum", pageNum);
		map.put("studyState", learningState);
		return map;
	}

	/**
	 * 获取到期提示
	 * @author	王宏伟
	 * @Date	2018年12月20日
	 */
	private void getHints(MyStudyDto studyCourseDto, Integer userId) {
		Integer courseId = studyCourseDto.getCourseId();
		//		PersonCourseScoreDto findStudentScore = studentOtherCourseScoreViewService.findStudentScore(courseId, userId);
		//		double courseScore = findStudentScore.getCourseScore();
		//		studyCourseDto.setCourseScore(courseScore);
		Sql sql = Sqls.create(sqlManager.get("minapp_mystudy_beoverdue_tips"));
		sql.setParam("courseId", courseId); //199
		sql.setParam("useStatus", YesOrNoEnum.YES.intKey());//使用状态
		sql.setParam("isDelete", YesOrNoEnum.NO.intKey());//是否删除
		sql.setParam("userId", userId);//用户id 32
		List<ExpireDto> expireDto = DbSqlUtil.query(dbDao, ExpireDto.class, sql);
		int size = expireDto.size();
		if (size == 0) {
			studyCourseDto.setRecordBoolean(false);
		} else if (size == 1) {
			studyCourseDto.setTypeStatus(expireDto.get(0).getTypeStatus());
			studyCourseDto.setCourseStruId(expireDto.get(0).getCourseStruId());
			studyCourseDto.setRecordId(expireDto.get(0).getId());
			studyCourseDto.setRecordBoolean(true);
		} else {
			if (expireDto.get(0).getRemainingSeconds() == expireDto.get(1).getRemainingSeconds()) {
				if (expireDto.get(0).getTypeStatus() == CurriculumResourcesEnum.TESTPAPER.intKey()) {
					studyCourseDto.setTypeStatus(expireDto.get(0).getTypeStatus());
					studyCourseDto.setCourseStruId(expireDto.get(0).getCourseStruId());
					studyCourseDto.setRecordId(expireDto.get(0).getId());
				} else if (expireDto.get(1).getTypeStatus() == CurriculumResourcesEnum.TESTPAPER.intKey()) {
					studyCourseDto.setTypeStatus(expireDto.get(1).getTypeStatus());
					studyCourseDto.setCourseStruId(expireDto.get(1).getCourseStruId());
					studyCourseDto.setRecordId(expireDto.get(1).getId());
				}
			} else {
				studyCourseDto.setTypeStatus(expireDto.get(0).getTypeStatus());
				studyCourseDto.setCourseStruId(expireDto.get(0).getCourseStruId());
				studyCourseDto.setRecordId(expireDto.get(0).getId());
			}
			studyCourseDto.setRecordBoolean(true);
		}
	}

	public Map<String, Object> studyStateEnum() {
		//枚举- 将map转为list
		Map<String, String> map = EnumUtil.enum2(StudyStateEnum.class);
		List<Map<String, String>> studyStateEnum = Lists.newArrayList();
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			Map<String, String> each = Maps.newHashMap();
			each.put("key", key);
			each.put("value", map.get(key));
			studyStateEnum.add(each);
		}
		//存入map
		Map<String, Object> obj = MapUtil.map();
		//订单状态枚举
		obj.put("studyStateEnum", studyStateEnum);
		return obj;
	}

	/**
	 *	获取每个学习状态的数量
	 */
	public MyCourseTotalDto myStudyCount(Integer userId) {
		//查询课程中每个状态的总数量		STUDYCENTRE(1, "学习中"), STUDYCOMPLETE(2, "学习完");
		Sql courseCountSql = Sqls.create(sqlManager.get("wx_mystudy_course_count"));
		courseCountSql.setParam("userId", userId);
		courseCountSql.setParam("series", OrderTypeEnum.COURSESERIES.intKey());
		courseCountSql.setParam("course", OrderTypeEnum.COURSE.intKey());
		courseCountSql.setParam("studycentre", StudyStateEnum.STUDYCENTRE.intKey());
		courseCountSql.setParam("studycomplete", StudyStateEnum.STUDYCOMPLETE.intKey());
		MyCourseTotalDto courseCount = DbSqlUtil.fetchEntity(dbDao, MyCourseTotalDto.class, courseCountSql);
		return courseCount;
	}

}
